package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: cn.com.callback-apiGetcontractList
 * @Description:ngsapitask-ph 根据模板id获取合同详情信息
 * @Author: 胡策富
 * @Date 2023/8/2 9:41
 *
 */
class apiGetcontractList implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetcontractList.class);
    //定义数据源常量
    private static final String DATA_SOURCE = "dataSource";

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        JSONObject result = new JSONObject();
        //获取入参报文
        String jsonBody = Util.getRequestBody(request, 'utf-8');
        log.debug("入参报文：" + jsonBody);
        //定义拼接查询字段
        String sqlField = "";
        //定义拼接展示名称
        String sqlFieldName = "";
        Integer currentPage = 0;
        try {
            //将入参封装致JSON对象
            JSONObject inPostJson = JSONObject.fromObject(jsonBody);
            //接收合同模板id
            String templateId = inPostJson.getString("templateId");
            //接收批次id
            String batchId = inPostJson.getString("batchId");
            //接收分页开始页
            Integer pageNo = inPostJson.getInt("pageNo");
            if (pageNo < 1 || pageNo == null) {
                currentPage = 1;
            } else {
                currentPage = pageNo;
            }
            //接收页大小
            Integer pageSize = inPostJson.getInt("pageSize");
            if (pageSize <= 0) {
                pageSize = 20;
            }
            //计算分页值
            pageNo = (currentPage - 1) * pageSize;
            //接收姓名
            String name = inPostJson.getString("name");
            //接收账号
            String accountNo = inPostJson.getString("accountNo");
            //接收所属部门
            String departmentId = inPostJson.getString("departmentId");
            //接收签署状态
            String fddStatus = inPostJson.getString("fddStatus");
            //获取合同详细信息字段
            String contractSql = "select label_id from ph_label_sign";
            List contractList = eliteBean.chaxun_sql(contractSql, DATA_SOURCE);
            //将合同详细信息字段封装至JSONArray
            JSONArray contractArray = JSONArray.fromObject(contractList);
            //根据合同模板获取展示的列
            String colLenSql = "SELECT keyname FROM fdd_contract_key where contractfileid = '" + templateId + "'";
            List colLenList = eliteBean.chaxun_sql(colLenSql, DATA_SOURCE);
            //将合同详细字段表头封装至JSONArray
            JSONArray colLenArray = JSONArray.fromObject(colLenList);
            log.debug("返回详细信息字段报文：" + colLenArray);
            //根据合同模板的列遍历合同详细信息字段
            for (int i = 0; i < colLenList.size(); i++) {
                JSONObject colLenObject = colLenArray.get(i);
                //获取展示名称
                String keyName = colLenObject.getString("keyname");
                sqlFieldName = sqlFieldName + "'" + keyName + "',";
            }
            sqlFieldName = sqlFieldName.substring(0,sqlFieldName.length() -1);
            //拼接详情sql
            String detailSql = "'rec_guid','批次号','推送状态','合同状态','失败原因','姓名','账号(手机/邮箱)','文件标题','所属部门','一体化客户号'," + sqlFieldName + "";
            String[] detaiArr = detailSql.split(",");
            for (int j = 0; j < detaiArr.length - 4; j++) {
                JSONObject contractObject = contractArray.get(j);
                //获取字段
                String LabelId = contractObject.getString("label_id");
                if(j == 1){
                    sqlField = sqlField + '''CASE `state` WHEN 0 THEN '未启用'
                    WHEN 1 THEN '等待推送'
                    WHEN 2 THEN '推送成功'
                    WHEN - 1 THEN '推送失败'
                    WHEN 3 THEN '暂停推送'
                    WHEN 4 then '批次已废弃'
                    END ,
                    f.type,
                    failed_resean,''' + LabelId + ",";
                }else{
                    sqlField = sqlField + LabelId + ",";
                }
            }
            sqlField = "rec_guid," + sqlField.substring(0, sqlField.length() - 1);
            log.debug("sqlField:" + sqlField);
            //获取详情总大小
            String detailCountSql = "select count(1) CON FROM ph_contract_sign_list where batch_id = '" + batchId + "'";
            Integer detailCount = eliteBean.chaxun_sql(detailCountSql, DATA_SOURCE)[0].getAt("CON");
            //总页数
            Integer totalPage = detailCount % pageSize == 0 ? detailCount / pageSize : (detailCount / pageSize) + 1;
            //上一页
            Integer upperPage = currentPage - 1;
            if (upperPage <= currentPage) {
                upperPage = currentPage;
            }
            //下一页
            Integer nextPage = currentPage + 1;
            if (nextPage >= totalPage) {
                nextPage = totalPage;
            }
            //查询合同详情
            StringBuffer contractDetailSql = new StringBuffer('''
                                        SELECT
                                        ''' + detailSql + ''' UNION ALL
                                            SELECT * 
                                               FROM 
                                               (SELECT 
                                               ''' + sqlField + '''
                                        FROM
                                            ph_contract_sign_list p
                                        LEFT JOIN fdd_status_type f on p.fdd_status = f.step
                                        left join sysc_rolegrouptype s1 on s1.ROLEGROUPTYPE = p.department_id
                                        WHERE
                                            batch_id = \'''' + batchId + '''\' 
                                        ''');
            if (name != null && name != "") {
                contractDetailSql.append(''' and name like concat('%',\'''' + name + '''\','%') ''');
            }
            if (accountNo != null && accountNo != "") {
                contractDetailSql.append(''' and account_no like concat('%',\'''' + accountNo + '''\','%') ''');
            }
            if (departmentId != null && departmentId != "") {
                contractDetailSql.append(''' and department_id  = \'''' + departmentId + '''\' ''');
            }
            if (fddStatus != null && fddStatus != "") {
                contractDetailSql.append(''' and fdd_status = ''' + fddStatus + ''' ''');
            }
            contractDetailSql.append('''order by created_date) t''');
            contractDetailSql.append()
            List contractDetailList = eliteBean.chaxun_sql(contractDetailSql.toString(), DATA_SOURCE);
            JSONArray contractDetailArray = JSONArray.fromObject(contractDetailList);
            log.debug("集合大小：" + contractDetailArray.size());
            result.put("responseCode", 200);
            result.put("responseMsg", "请求成功");
            result.put("data", contractDetailArray);
            result.put("currentPage", currentPage);
            result.put("pageSize", contractDetailArray.size() - 1);
            result.put("upperPage", upperPage + 1);
            result.put("nextPage", nextPage + 1);
            result.put("totalPage", totalPage);
        } catch (Exception e) {
            log.error("程序异常：" + e.getMessage());
            result.put("responseCode", 400);
            result.put("responseMsg", "请求失败");
        }
        return result;
    }
}
